package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.aliyun.GreenTextScan;
import com.heima.comment.dtos.CommentLikeDto;
import com.heima.comment.dtos.CommentListDto;
import com.heima.comment.dtos.CommentSaveDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feign.client.UserFeignClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.thread.ApThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 发表评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentSaveDto dto) {
        //1.校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser apUser = ApThreadLocal.getApUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.5是游客不允许评论

        if (apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "请登录后再来评论");
        }

        //查询用户信息  先从redis中查询 没有从微服务中查
        String apUserStr = redisTemplate.opsForValue().get("LOGIN_USER_" + apUser.getId());
        if (StringUtils.isBlank(apUserStr)) {//为空 表示第一次
            //远程调用接口查询
            ResponseResult<ApUser> responseResult = userFeignClient.findById(apUser.getId().longValue());

            if (responseResult.getCode() == 200 && responseResult.getData() == null) {
                apUser = responseResult.getData();

                //存入redis
                redisTemplate.opsForValue().set("LOGIN_USER_" + apUser.getId(), JSON.toJSONString(apUser), 2, TimeUnit.HOURS);

            }
        } else {
            apUser = JSON.parseObject(apUserStr, ApUser.class);
        }

        //评论审核
        boolean textScan = textScan(dto.getContent());
        if (!textScan) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论中包含敏感词汇");
        }


        //保存到minio
        ApComment apComment = new ApComment();
        apComment.setId(ObjectId.get().toHexString());
        apComment.setImage(apUser.getImage());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setTargetId(dto.getArticleId().toString());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setContent(dto.getContent());
        apComment.setUserId(apUser.getId());
        apComment.setNickName(apUser.getName());


        mongoTemplate.insert(apComment);
        return ResponseResult.okResult("评论成功");
    }

    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //1.校验参数

        if (dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser apUser = ApThreadLocal.getApUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.5游客登录 直接返回
        if (apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"当前操作需要登录");
        }

        //3.判断当前评论信息是否存在  不存在直接返回
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.1查询redis是否有点赞信息
        //定义likes_key
        String  comment_likes_key ="COMMENT_LIKES_"+apUser.getId();
        Boolean aBoolean = redisTemplate.opsForSet().isMember(comment_likes_key, dto.getCommentId());

        //4.如果已点赞并且执行的是点赞操作 直接返回
        if (aBoolean&&dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //5.点赞过并且执行的是取消点赞，删除redis，mongo中点赞集合，修改mongo中的评论集合，点赞数-1
        if (aBoolean&&dto.getOperation()==1){
            //删除 redis
            redisTemplate.opsForSet().remove(comment_likes_key,dto.getCommentId());
            //删除mongo
            mongoTemplate.remove(Query.query(Criteria
                    .where("userId").is(apUser.getId())
                    .and("targetId").is(dto.getCommentId())), ApCommentLike.class);


            //修改mongo中的评论集合，点赞数-1
            Query query=Query.query(Criteria.where("id").is(apComment.getId()).and("likes").gt(0));
            UpdateDefinition update=new Update().inc("likes",-1);
            mongoTemplate.updateFirst(query,update,ApComment.class);
        }

        //6 如果没有点赞过，并且正在执行的是点赞操作，新增redis,新增mongo中的点赞集合，修改mongo中的评论集合，点赞数+1
        if (!aBoolean&&dto.getOperation()==0){
            //新增redis
            redisTemplate.opsForSet().add(comment_likes_key,dto.getCommentId());

            //新增mongo中的点赞集合
            ApCommentLike apCommentLike =new ApCommentLike();
            apCommentLike.setId(ObjectId.get().toHexString());
            apCommentLike.setTargetId(dto.getCommentId());
            apCommentLike.setCreatedTime(new Date());
            apCommentLike.setUserId(apUser.getId());
            mongoTemplate.insert(apCommentLike);

            //修改mongo中的评论集合  点赞+1
            Query query = Query.query(Criteria.where("id").is(apCommentLike.getId()));
            UpdateDefinition upDate=new Update().inc("likes",1);
            mongoTemplate.updateFirst(query,upDate,ApComment.class);
        }

        //返回数据
        apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);

        Map map =new HashMap();

        map.put("likes",apComment.getLikes());

        return ResponseResult.okResult(map);

    }

    /**
     * 加载文章评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentListDto dto) {

        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), 50));

        //2根据文章id去查询mongo的评论表，并进行分页和排序展示
        Query query=Query.query(Criteria.where("targetId").is(dto.getArticleId().toString())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime")) //排序
                .limit(dto.getSize()); //分页
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        if(commentList==null && commentList.size()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.如果此刻是游客登录的话，则直接返回评论列表
        ApUser user = ApThreadLocal.getApUser();
        if(user.getId()==0){
            return ResponseResult.okResult(commentList);
        }
        //4.否则就是用户登录，加载数据的时候，要判断当前用户点赞了拿些评论，并给予标识
        //4.1 查询redis中是否有点赞数据
        String key="COMMENT_LIKE_"+user.getId();
        //根据key查询出所有的值
        Set<String> like_ids = redisTemplate.opsForSet().members(key);
        //4.2 如果没有查询到数据,则直接返回评论列表
        if(like_ids==null){
            return ResponseResult.okResult(commentList);
        }
        //4.3 否则，就是存在点赞数据，则添加标记
        List<ApCommentVo> resultList = commentList.stream().map(comment -> {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(comment, vo);
            if (like_ids.contains(comment.getId())) {
                vo.setOperation((short) 0);
            }
            return vo;

        }).collect(Collectors.toList());
        //5. 返回数据

        return ResponseResult.okResult(resultList);
    }


    /**
     * 抽取审核文本的方法
     *
     * @param content
     * @return
     */
    private boolean textScan(String content) {

        boolean flag = true;
        try {
            Map scanTextMap = greenTextScan.greeTextScan(content);
            //违规，审核不通过
            if (scanTextMap.get("suggestion").equals("block")) {
                flag = false;
            }
            //表示需要人工审核
            if (scanTextMap.get("suggestion").equals("review")) {
                flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
